package com.study.mybatis.session.defaults;

import com.study.mybatis.executor.Executor;
import com.study.mybatis.executor.SimpleExecutor;
import com.study.mybatis.mapping.MappedStatement;
import com.study.mybatis.session.Configuration;
import com.study.mybatis.session.SqlSession;

import java.util.List;

/**
 * @author yuantongqin
 * 2021/7/31
 **/
public class DefaultSqlSession implements SqlSession {

    private Executor executor;
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.executor = new SimpleExecutor(configuration);
    }


    @Override
    public <T> T selectOne(String methodId) {
        return null;
    }

    @Override
    public <T> T selectOne(String methodId, Object parameter) {
        List<T> results = this.<T> selectList(methodId, parameter);
        if(results != null && results.size() >0 ){
            return results.get(0);
        }
        return null;
    }

    @Override
    public <T> List<T> selectList(String methodId, Object parameter) {
        MappedStatement mappedStatement = this.configuration.getMapper(methodId);
        mappedStatement.setConfiguration(this.configuration);
        return this.executor.<T> doQuery(mappedStatement, parameter);

    }

    @Override
    public <T> T getMapper(Class<T> type) {
        return configuration.getMapperRegistry().getMapper(type,this);
    }

    @Override
    public Configuration getConfig() {
        return this.configuration;
    }
}
